﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Qianke.Core.Saas.WebApi.SaasExtensions.Model
{
    public class IntegerToStringConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            // 返回 true 如果这个转换器可以处理指定的对象类型
            return objectType == typeof(int) || objectType == typeof(int?) ||
                objectType == typeof(long) || objectType == typeof(long?) ||
                objectType == typeof(short) || objectType == typeof(short?) ||
                objectType == typeof(byte) || objectType == typeof(byte?) ||
                objectType == typeof(uint) || objectType == typeof(uint?) ||
                objectType == typeof(ulong) || objectType == typeof(ulong?) ||
                objectType == typeof(ushort) || objectType == typeof(ushort?) ||
                objectType == typeof(sbyte) || objectType == typeof(sbyte?) ||
                objectType == typeof(decimal) || objectType == typeof(decimal?) ||
                objectType == typeof(float) || objectType == typeof(float?) ||
                objectType == typeof(double) || objectType == typeof(double?) || objectType.IsEnum;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // 读取 JSON 数据并将其转换为整型
            object val = reader.Value;

            if (reader.TokenType == JsonToken.Null)
            {
                if (objectType.Name.StartsWith("Nullable"))
                    return null;
                return Activator.CreateInstance(objectType);
            }
            if (objectType.IsEnum)
                return Enum.Parse(objectType, reader.Value.ToString());

            if (objectType.Name.StartsWith("Nullable"))
            {
                try
                {
                    return Convert.ChangeType(val, objectType.GenericTypeArguments[0]);
                }
                catch (Exception)
                {
                    return null;
                }
            }
            try
            {
                return Convert.ChangeType(val, objectType);
            }
            catch (Exception)
            {
                return Activator.CreateInstance(objectType);
            }

        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value.GetType().IsEnum)
                writer.WriteValue(Convert.ToInt64(value).ToString());
            else
            {
                // 将整型值转换为字符串并写入 JSON
                writer.WriteValue(value?.ToString());
            }
        }
    }
}
